package com.kele.service.impl;

import com.kele.entity.Student;
import com.kele.mapper.StudentMapper;
import com.kele.service.StudentService;
import com.kele.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kele
 * @date 2021/8/12 11:50
 * @description
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public List<Student> findAll() {

        List<Student> students= studentMapper.findAll();
        redisUtil.set("studentAll",students);
        return students;
    }

    @Override
    public Student findStudentById(Integer id) {

        Student student = studentMapper.findStudentById(id);
        redisUtil.set("student"+id,student);
        return student;
    }

    @Override
    public Student findStudentByName(String name) {
        return studentMapper.findStudentByName(name);
    }

    @Override
    public int updateStudent(Student student) {
        int res = studentMapper.updateStudent(student);
        if (res>0){
            return res;
        }
        return 0;
    }

    @Override
    public int deleteStudent(Integer id) {
        int res = studentMapper.deleteStudent(id);
        if (res>0){
            return res;
        }
        return 0;
    }

    @Override
    public int insertStudent(Student student) {
        //先删除缓存中的值
        redisUtil.del("studentAll");
        //再更新数据库
        int res = studentMapper.insertStudent(student);
        //再查询所有

        List<Student> students = studentMapper.findAll();
        if (res>0&& students.size()!=0){
            //写入缓存
            boolean studentAll = redisUtil.set("studentAll", students);
            if (studentAll){
                return 1;
            }

        }
        return 0;
    }
}
